//
//  GPImagePickerController.swift
//  SeaTransportManage
//
//  Created by guopengwen on 2021/12/5.
//

import UIKit
import Foundation
import AssetsLibrary
import Photos

class GPImagePickerController: GPBaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    /**************** 屏幕底部弹出的 Alert: 相机、相册 *********/
    func showPickPictrueSheet(){
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let cancel = UIAlertAction(title:"取消", style: .cancel, handler: nil)
        let takingPictures = UIAlertAction(title:"拍照", style: .default) {
            action in
            self.tackPictureFromCamera()
        }
        let localPhoto = UIAlertAction(title:"相册", style: .default) {
            action in
            self.pickPhotoFromAlbum()
        }
        alertController.addAction(cancel)
        alertController.addAction(takingPictures)
        alertController.addAction(localPhoto)
        self.present(alertController, animated:true, completion:nil)
    }
    
    func tackPictureFromCamera() {
        let status = AVCaptureDevice.authorizationStatus(for: .video);
        switch status {
            case .authorized:
                self.initCameraPicker()
                break
            case .notDetermined:
                AVCaptureDevice.requestAccess(for: .video, completionHandler: {
                    (granted : Bool) in
                    if (granted == true) {
                        self.initCameraPicker()
                    } else {
                        print("%@","Not Camera Determined")
                    }
                })
                break
            case .denied,
                 .restricted:
                MTAlert.presentAlert(title: "提醒", message: "请在\"设置\"-\"隐私\"-\"相机\"中允许海铁货运访问您的相机", cancelButtonTitle: "好的", otherButtonTitles: nil, clickedButtonAtIndex: {
                    (buttonIndex) in
                    _ = self.navigationController?.popViewController(animated: true);
                })
                break
            default: break
        }
    }
    
    func pickPhotoFromAlbum() {
        if #available(iOS 14, *) {
            let sta = PHPhotoLibrary.authorizationStatus(for: .addOnly)
            switch sta {
                case .authorized:
                    //允许访问所有的相册
                    self.initPhotoPicker()
                    break
                case .notDetermined:
                    //权限未指定
                    PHPhotoLibrary.requestAuthorization(for: .addOnly) {
                        status in
                        if(status == .authorized) {
                            self.initPhotoPicker()
                        } else {
                            print("%@","Not Photo Determined")
                        }
                    }
                    break
                case .denied,
                     .limited:
                    //访问部分相册受限
                    MTAlert.presentAlert(title: "提醒", message: "请在\"设置\"-\"隐私\"-\"相机\"中允许海铁货运访问您的相机", cancelButtonTitle: "好的", otherButtonTitles: nil, clickedButtonAtIndex: {
                        (buttonIndex) in
                        self.navigationController?.popViewController(animated: true);
                    })
                    break
                default: break
            }
        } else {
            let sta = PHPhotoLibrary.authorizationStatus()
            switch sta {
                case .authorized:
                    //允许访问所有的相册
                    self.initPhotoPicker()
                    break
                case .notDetermined:
                    //权限未指定
                    PHPhotoLibrary.requestAuthorization() {
                        status in
                        if(status == .authorized) {
                            self.initPhotoPicker()
                        } else {
                            print("%@","Not Photo Determined")
                        }
                    }
                    break
                case .denied,
                     .limited:
                    //访问部分相册受限
                    MTAlert.presentAlert(title: "提醒", message: "请在\"设置\"-\"隐私\"-\"相机\"中允许海铁货运访问您的相机", cancelButtonTitle: "好的", otherButtonTitles: nil, clickedButtonAtIndex: {
                        (buttonIndex) in
                        self.navigationController?.popViewController(animated: true);
                    })
                    break
                default: break
            }
        }
    }
    
    //拍照
    func initCameraPicker() {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            DispatchQueue.main.async {
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = true
                cameraPicker.sourceType = .camera
                //在需要的地方present出来
                self.present(cameraPicker, animated: true, completion: nil)
            }
        } else {
            print("不支持拍照")
        }
    }
    
    //从相册中选择
    func initPhotoPicker(){
        DispatchQueue.main.async {
            let photoPicker =  UIImagePickerController()
            photoPicker.delegate = self
            photoPicker.allowsEditing = true
            photoPicker.sourceType = .photoLibrary
            //在需要的地方present出来
            self.present(photoPicker, animated: true, completion: nil)
        }
    }
    
    // UIImagePickerControllerDelegate, UINavigationControllerDelegate
    //拍照或是相册选择返回的图片
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        
        //将选择的图片保存到Document目录下
        let  fileManager =  FileManager.default
        let  rootPath =  NSSearchPathForDirectoriesInDomains (.documentDirectory, .userDomainMask,  true )[0]  as  String
        let timeInterval: TimeInterval = Date.init().timeIntervalSince1970
        let  filePath =  "\(rootPath)/pic-\(timeInterval).jpg"
        let  imageData =  image.jpegData (compressionQuality: 1.0)
        fileManager.createFile(atPath: filePath, contents: imageData, attributes:  nil )
        handleImagePickerResult(image, filePath)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    // 子类可继该方法，对获取到的照片进行处理
    func handleImagePickerResult (_ image: UIImage, _ filePath: String) {
        
    }
    
}
